#!/usr/bin/env python3
"""数据模型和接口演示

本示例演示如何使用MCP决策优化服务的核心数据结构和接口功能。
"""

import json
import sys
import os

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
sys.path.insert(0, os.path.join(project_root, 'src'))

from src.models import (
    DecisionVariable, ObjectiveFunction, Constraint, UncertaintyParameter,
    OptimizationProblem, AlgorithmConfig, OptimizationResult,
    VariableType, OptimizationType, ConstraintType, UncertaintyType, AlgorithmType
)

# 简化演示，直接使用数据结构，不依赖FastMCP接口
# 创建简化的辅助函数来演示功能

def get_variable_types():
    """获取支持的变量类型"""
    return [vtype.value for vtype in VariableType]

def get_optimization_types():
    """获取支持的优化类型"""
    return [otype.value for otype in OptimizationType]

def get_constraint_types():
    """获取支持的约束类型"""
    return [ctype.value for ctype in ConstraintType]

def get_uncertainty_types():
    """获取支持的不确定性类型"""
    return [utype.value for utype in UncertaintyType]

def get_algorithm_types():
    """获取支持的算法类型"""
    return [atype.value for atype in AlgorithmType]

def validate_problem_data(problem):
    """验证问题数据"""
    try:
        # 验证变量
        for var in problem.variables:
            if not var.is_valid():
                return {"valid": False, "message": f"变量 {var.name} 无效"}
        
        # 验证目标函数
        if not problem.objectives:
            return {"valid": False, "message": "至少需要一个目标函数"}
        
        # 验证约束
        for constraint in problem.constraints:
            if not constraint.is_valid():
                return {"valid": False, "message": f"约束 {constraint.name} 无效"}
        
        return {"valid": True, "message": "问题数据验证通过"}
    except Exception as e:
        return {"valid": False, "message": f"验证过程中发生错误: {str(e)}"}

def get_data_model_summary():
    """获取数据模型摘要"""
    return {
        "variable_types": len(VariableType),
        "optimization_types": len(OptimizationType),
        "constraint_types": len(ConstraintType),
        "uncertainty_types": len(UncertaintyType),
        "algorithm_types": len(AlgorithmType),
        "description": "MCP决策优化服务数据模型"
    }


def demo_basic_data_models():
    """演示基础数据模型的创建和使用"""
    print("=" * 60)
    print("基础数据模型演示")
    print("=" * 60)
    
    # 1. 创建决策变量
    print("\n1. 创建决策变量:")
    x1 = DecisionVariable(
        name="production_x1",
        variable_type=VariableType.CONTINUOUS,
        lower_bound=0.0,
        upper_bound=1000.0,
        initial_value=100.0,
        description="产品1的生产量"
    )
    
    x2 = DecisionVariable(
        name="production_x2",
        variable_type=VariableType.INTEGER,
        lower_bound=0,
        upper_bound=500,
        initial_value=50,
        description="产品2的生产量"
    )
    
    print(f"变量1: {x1.name} ({x1.variable_type.value}) [{x1.lower_bound}, {x1.upper_bound}]")
    print(f"变量2: {x2.name} ({x2.variable_type.value}) [{x2.lower_bound}, {x2.upper_bound}]")
    print(f"变量1有效性: {x1.is_valid()}")
    print(f"变量2有效性: {x2.is_valid()}")
    
    # 2. 创建目标函数
    print("\n2. 创建目标函数:")
    profit_obj = ObjectiveFunction(
        name="maximize_profit",
        optimization_type=OptimizationType.MAXIMIZE,
        expression="50*x1 + 30*x2",
        weight=1.0,
        description="最大化利润"
    )
    
    cost_obj = ObjectiveFunction(
        name="minimize_cost",
        optimization_type=OptimizationType.MINIMIZE,
        expression="10*x1 + 15*x2",
        weight=0.5,
        description="最小化成本"
    )
    
    print(f"目标函数1: {profit_obj.name} ({profit_obj.optimization_type.value})")
    print(f"表达式: {profit_obj.expression}")
    print(f"目标函数2: {cost_obj.name} ({cost_obj.optimization_type.value})")
    print(f"表达式: {cost_obj.expression}")
    
    # 3. 创建约束条件
    print("\n3. 创建约束条件:")
    resource_constraint = Constraint(
        name="resource_limit",
        constraint_type=ConstraintType.INEQUALITY,
        expression="2*x1 + 3*x2",
        rhs_value=1500.0,
        tolerance=1e-6,
        description="资源限制"
    )
    
    demand_constraint = Constraint(
        name="demand_requirement",
        constraint_type=ConstraintType.EQUALITY,
        expression="x1 + x2",
        rhs_value=200.0,
        tolerance=1e-6,
        description="需求要求"
    )
    
    print(f"约束1: {resource_constraint.name} ({resource_constraint.constraint_type.value})")
    print(f"表达式: {resource_constraint.expression} <= {resource_constraint.rhs_value}")
    print(f"约束2: {demand_constraint.name} ({demand_constraint.constraint_type.value})")
    print(f"表达式: {demand_constraint.expression} = {demand_constraint.rhs_value}")
    
    # 4. 创建不确定性参数
    print("\n4. 创建不确定性参数:")
    demand_uncertainty = UncertaintyParameter(
        name="market_demand",
        uncertainty_type=UncertaintyType.NORMAL,
        parameters={"mean": 200.0, "std": 20.0},
        description="市场需求的不确定性"
    )
    
    price_uncertainty = UncertaintyParameter(
        name="product_price",
        uncertainty_type=UncertaintyType.UNIFORM,
        parameters={"low": 45.0, "high": 55.0},
        description="产品价格的不确定性"
    )
    
    print(f"不确定性参数1: {demand_uncertainty.name} ({demand_uncertainty.uncertainty_type.value})")
    print(f"参数: {demand_uncertainty.parameters}")
    demand_samples = demand_uncertainty.sample(5)
    print(f"采样示例: {[round(s, 2) for s in demand_samples]}")
    
    print(f"\n不确定性参数2: {price_uncertainty.name} ({price_uncertainty.uncertainty_type.value})")
    print(f"参数: {price_uncertainty.parameters}")
    price_samples = price_uncertainty.sample(5)
    print(f"采样示例: {[round(s, 2) for s in price_samples]}")
    
    # 5. 创建优化问题
    print("\n5. 创建优化问题:")
    problem = OptimizationProblem(
        name="production_planning",
        variables=[x1, x2],
        objectives=[profit_obj, cost_obj],
        constraints=[resource_constraint, demand_constraint],
        uncertainty_params=[demand_uncertainty, price_uncertainty],
        description="生产计划优化问题"
    )
    
    print(f"问题名称: {problem.name}")
    print(f"变量数量: {len(problem.variables)}")
    print(f"目标函数数量: {len(problem.objectives)}")
    print(f"约束条件数量: {len(problem.constraints)}")
    print(f"不确定性参数数量: {len(problem.uncertainty_params)}")
    print(f"是否多目标优化: {problem.is_multi_objective()}")
    print(f"是否包含不确定性: {problem.has_uncertainty()}")
    
    # 6. 创建算法配置
    print("\n6. 创建算法配置:")
    ga_config = AlgorithmConfig(
        algorithm_type=AlgorithmType.GENETIC_ALGORITHM,
        parameters={
            "population_size": 100,
            "mutation_rate": 0.1,
            "crossover_rate": 0.8,
            "selection_method": "tournament"
        },
        max_iterations=1000,
        tolerance=1e-6,
        random_seed=42
    )
    
    print(f"算法类型: {ga_config.algorithm_type.value}")
    print(f"自定义参数: {ga_config.parameters}")
    print(f"最大迭代次数: {ga_config.max_iterations}")
    print(f"收敛容差: {ga_config.tolerance}")
    
    defaults = ga_config.get_default_parameters()
    print(f"默认参数: {defaults}")
    
    return problem, ga_config


def demo_interface_functions():
    """演示接口函数的使用"""
    print("\n" + "=" * 60)
    print("接口函数演示")
    print("=" * 60)
    
    # 1. 获取支持的类型
    print("\n1. 获取支持的类型:")
    print("\n变量类型:")
    print(get_variable_types())
    
    print("\n优化类型:")
    print(get_optimization_types())
    
    print("\n约束类型:")
    print(get_constraint_types())
    
    print("\n不确定性类型:")
    print(get_uncertainty_types())
    
    print("\n算法类型:")
    print(get_algorithm_types())
    
    # 2. 创建决策变量
    print("\n2. 创建决策变量:")
    interface_var = DecisionVariable(
        name="interface_var",
        variable_type=VariableType.CONTINUOUS,
        lower_bound=0.0,
        upper_bound=100.0,
        initial_value=50.0,
        description="通过接口创建的变量"
    )
    print(f"创建成功: {interface_var.name}, 类型: {interface_var.variable_type.value}")
    
    # 3. 创建目标函数
    print("\n3. 创建目标函数:")
    interface_objective = ObjectiveFunction(
        name="interface_objective",
        optimization_type=OptimizationType.MINIMIZE,
        expression="x**2 + y**2",
        weight=1.0,
        description="通过接口创建的目标函数"
    )
    print(f"创建成功: {interface_objective.name}, 类型: {interface_objective.optimization_type.value}")
    
    # 4. 创建约束条件
    print("\n4. 创建约束条件:")
    interface_constraint = Constraint(
        name="interface_constraint",
        constraint_type=ConstraintType.INEQUALITY,
        expression="x + y",
        rhs_value=10.0,
        description="通过接口创建的约束条件"
    )
    print(f"创建成功: {interface_constraint.name}, 类型: {interface_constraint.constraint_type.value}")
    
    # 5. 创建不确定性参数
    print("\n5. 创建不确定性参数:")
    interface_uncertainty = UncertaintyParameter(
        name="interface_uncertainty",
        uncertainty_type=UncertaintyType.NORMAL,
        parameters={"mean": 100.0, "std": 15.0},
        description="通过接口创建的不确定性参数"
    )
    print(f"创建成功: {interface_uncertainty.name}, 类型: {interface_uncertainty.uncertainty_type.value}")
    
    # 6. 创建优化问题
    print("\n6. 创建优化问题:")
    
    # 创建变量
    x_var = DecisionVariable(
        name="x",
        variable_type=VariableType.CONTINUOUS,
        lower_bound=0.0,
        upper_bound=10.0,
        description="变量x"
    )
    
    y_var = DecisionVariable(
        name="y",
        variable_type=VariableType.CONTINUOUS,
        lower_bound=0.0,
        upper_bound=10.0,
        description="变量y"
    )
    
    # 创建目标函数
    distance_obj = ObjectiveFunction(
        name="minimize_distance",
        optimization_type=OptimizationType.MINIMIZE,
        expression="sqrt(x**2 + y**2)",
        weight=1.0,
        description="最小化距离"
    )
    
    # 创建约束
    circle_constraint = Constraint(
        name="circle_constraint",
        constraint_type=ConstraintType.INEQUALITY,
        expression="x**2 + y**2",
        rhs_value=25.0,
        description="圆形约束"
    )
    
    # 创建完整问题
    interface_problem = OptimizationProblem(
        name="interface_problem",
        variables=[x_var, y_var],
        objectives=[distance_obj],
        constraints=[circle_constraint],
        description="通过接口创建的优化问题"
    )
    print(f"问题创建成功: {interface_problem.name}")
    print(f"变量数量: {len(interface_problem.variables)}")
    print(f"目标函数数量: {len(interface_problem.objectives)}")
    print(f"约束数量: {len(interface_problem.constraints)}")
    
    # 7. 创建算法配置
    print("\n7. 创建算法配置:")
    interface_config = AlgorithmConfig(
        algorithm_type=AlgorithmType.GENETIC_ALGORITHM,
        parameters={"population_size": 50, "mutation_rate": 0.05},
        max_iterations=500,
        tolerance=1e-5,
        random_seed=123
    )
    print(f"配置创建成功: {interface_config.algorithm_type.value}")
    
    # 8. 验证问题数据
    print("\n8. 验证问题数据:")
    validation_result = validate_problem_data(interface_problem)
    print(f"验证结果: {validation_result}")
    
    # 9. 获取数据模型摘要
    print("\n9. 获取数据模型摘要:")
    summary = get_data_model_summary()
    print(f"摘要信息: {summary}")


def main():
    """主函数"""
    print("MCP决策优化服务 - 数据模型和接口演示")
    print("版本: 2.0.0")
    print("阶段: 核心数据结构与接口设计")
    
    try:
        # 演示基础数据模型
        problem, config = demo_basic_data_models()
        
        # 演示接口函数
        demo_interface_functions()
        
        print("\n" + "=" * 60)
        print("演示完成！")
        print("=" * 60)
        print("\n核心功能已实现:")
        print("✓ 决策变量定义和管理")
        print("✓ 目标函数创建和配置")
        print("✓ 约束条件设置和验证")
        print("✓ 不确定性参数建模")
        print("✓ 优化问题构建和存储")
        print("✓ 算法配置管理")
        print("✓ 数据验证和摘要")
        print("✓ 标准化接口设计")
        
        print("\n下一步开发建议:")
        print("- 实现核心优化算法")
        print("- 添加结果分析功能")
        print("- 完善不确定性处理")
        print("- 增强数据可视化")
        
    except Exception as e:
        print(f"\n演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()